package cn.qy.java.base.ch21;

import java.util.Random;

/**
 * @author acc8226
 */
public class Ch21_07_SameEnd {

	static class MyLatch {
		// 初始值为未完成的线程数，当减为 0 时表示 OK
		volatile int count;
		
		public MyLatch(int count) {
			this.count = count;
		}

		public synchronized void await() throws InterruptedException {
			// 使用 while，防止虚假唤醒
			while (count > 0) {
				wait();
			}
		}

		public synchronized void countDown() throws InterruptedException {
			count--;
			if (count <= 0) {
				notifyAll();
			}
		}
	}
	
	static class SameEndThread extends Thread {

		MyLatch latch;

		public SameEndThread(MyLatch latch) {
			this.latch = latch;
		}

		public void run() {
			try {
				long mills = new Random().nextInt(5000);
				Thread.sleep(mills);
				this.xxx(mills);
				this.latch.countDown();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		};

		private void xxx(long mills) {
			System.out.println("lalala after " + mills);
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		int size = 8;
		MyLatch latch = new MyLatch(size);
		for(int i = 0; i<size; i++) {
			new SameEndThread(latch).start();
		}
		latch.await();
		System.out.println("main thread over");
	}
}
